var TOAST_TIMEOUT = 2000;//ms
var MSG_TIMEOUT = 1000;//ms

function human_datetime(selector)
{
    $(selector).each(function(){
        var container = $(this);
        var t = container.text();
        container.attr('title', t);
        var tt = (new Date() - new Date(t)) / 1000;
        if (tt < 60) {
            container.text("刚刚");
            return;
        }
        tt /= 60;
        if (tt < 60) {
            container.text(Math.floor(tt)+"分钟前");
            return;
        }
        tt /= 60;
        if (tt < 24) {
            container.text(Math.floor(tt)+"小时前");
            return;
        }
        tt /= 24;
        if (tt < 30) {
            container.text(Math.floor(tt)+"天前");
            return;
        }
        tt /= 30;
        if (tt < 12) {
            container.text(Math.floor(tt)+"个月前");
            return;
        }
        tt /= 12;
        container.text(Math.floor(tt)+"年前");
    });
}

function form_submit_ajax(form){
    // do HTML escape first
    form.find(':text,:password,textarea').each(function(){
        $(this).prop('disabled', true);
        var v = $(this).val();
        v = $('<div>').text(v).html();
        $(this).val(v);
        $(this).prop('disabled', false);
    });
    // NOTE that input[type=file] cannot be serialize,
    //   so you shall not set the class of the form to ajax.
    var params = form.serialize(); // do it before code is set to ''
    // NOTE: TEXTAREA cannot be serialized
    form.find('textarea').each(function(){
        var name = $(this).attr('name');
        if (!name) return true;
        var v = $(this).val();
        params += (params?'&':'');
        params += encodeURIComponent(name) +'='+ encodeURIComponent(v);
    });
    // NOTE: input[type=file] cannot be serialized
    if (form.find(':file').length > 0) {
        toastr.error('上传文件不能使用AJAX');
        return false;
    }
    $.ajax({
        type: "POST",
        url: form.attr("action")||location.href,
        data: params,
        success: function(data, status){
            if (status != 'success') {
                toastr.error('请求失败！' + status);
                return false;
            }
            var json = JSON.parse(data);
            if (json.success) {
                // clear all input text
                form.find(':text,:password,textarea').each(function(){
                    $(this).val('');
                });
            }
            if (json.message) {
                if (json.success)
                    toastr.success(json.message);
                else
                    toastr.error(json.message);
            }
            if (json.script) {
                if (json.message)
                    setTimeout(json.script, MSG_TIMEOUT);
                else
                    eval(json.script);
            }
            if (json.redirect) {
                if (json.message)
                    setTimeout("location.href="+json.redirect, MSG_TIMEOUT);
                else
                    location.href = json.redirect;
            }
        },
        error: function(obj, status){
            toastr.error('出错了！(' +obj.status+ ' ' +obj.statusText+ ')');
        },
        complete: function(){
            $(':password').val('');// clear password
            form.find('input[name="code"]').val(''); // clear verify code
            form.find('img.code').click();// reset verify code image
            $('[autofocus]').focus();
        },
    });
    return false;
}

(function(window) {
    $('a.post').click(function(){
        $.post($(this).attr('href'));
        return false;
    });

    $.post("/is_online", function(data, status, xhr){
        if (data === "1") {// I am online
            $("#nav_login").hide();
            $("#nav_newblog, #nav_logout").show();
        } else {
            $("#nav_login a").attr("href", "/login?referer="+encodeURIComponent(location.href));
        }
    });

    $("textarea").bind("input", function(){
        var o = $(this)[0];
        o.style.height = o.scrollTop + o.scrollHeight + "px";
    });

    $('form.ajax').submit(function(){
        return form_submit_ajax($(this));
    });

    /* toast */
    toastr.options = {
        "closeButton": false,
        "positionClass": "toast-top-center",
        "onclick": null,
        "showDuration": "300",
        "hideDuration": "1000",
        "timeOut": TOAST_TIMEOUT,
        "extendedTimeOut": "1000",
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "fadeIn",
        "hideMethod": "fadeOut"
    };
}(window));
